module.exports = (app) => {
  const hmac = require("../../plugins/hmac")
  const router = require("express").Router({
    // 合并父子路由路径参数
    mergeParams: true,
  })
  //资源路径 转 数据库文件名

  app.use(
    "/admin/api/rest/:resource",
    async (req, res, next) => {
      const modelName = require("inflection").classify(req.params.resource)
      req.Model = require(`../../models/${modelName}`)
      next()
    },
    router
  )

  //创建API create
  router.post("/", async (req, res) => {
    if (req.Model.modelName === "User") {
      req.body.password = await hmac(req.body.password)
    }
    await req.Model.create(req.body, (err, model) => {
      if (err) {
        //返回分区已存在错误
        res.send(err)
      } else {
        //返回创建分区成功
        res.send(model)
      }
    })
  })
  //查询API read
  router.get("/", async (req, res) => {
    const queryOptions = {}
    if (req.Model.modelName === "Video") {
      queryOptions.populate = ["author", "type"]
    } else if (req.Model.modelName === "Live") {
      queryOptions.populate = ["user"]
    } else if (req.Model.modelName === "User") {
      queryOptions.populate = ["collectList", "attentionList"]
    } else if (req.Model.modelName === "Message") {
      queryOptions.populate = ["comment", "you", "user"]
    } else if (req.Model.modelName === "Comment") {
      queryOptions.populate = ["author", "from", "to"]
    }
    const data = await req.Model.find().setOptions(queryOptions)
    res.send(data)
  })
  //查询单个数据
  router.get("/:_id", async (req, res) => {
    const queryOptions = {}
    if (req.Model.modelName === "Video") {
      queryOptions.populate = ["author", "type"]
    } else if (req.Model.modelName === "Live") {
      queryOptions.populate = ["user"]
    } else if (req.Model.modelName === "User") {
      queryOptions.populate = ["collectList", "attentionList"]
    } else if (req.Model.modelName === "Message") {
      queryOptions.populate = ["comment", "you", "user"]
    } else if (req.Model.modelName === "Comment") {
      queryOptions.populate = ["author", "from", "to"]
    }
    const data = await req.Model.findById(req.params._id).setOptions(
      queryOptions
    )
    res.send(data)
  })
  //修改API update
  router.put("/", async (req, res) => {
    await req.Model.findByIdAndUpdate(req.body._id, req.body, (err, model) => {
      if (err) {
        res.send(err)
      } else {
        res.send(model)
      }
    })
  })
  //删除API delete
  router.delete("/", async (req, res) => {
    console.log({ _id: { $in: req.body } })
    const model = await req.Model.deleteMany({ _id: { $in: req.body } })

    res.send(true)
  })
  //单个删除
  router.delete("/:_id", async (req, res) => {
    const model = await req.Model.findByIdAndDelete(req.params._id)
    res.send(true)
  })

  //上传文件路由
  const fs = require("fs")
  // 导入异步处理器 (promise化)
  const { promisify } = require("util")
  //异步处理pipeline
  const pipeline = promisify(require("stream").pipeline)
  const upload = require("multer")({ limits: { fileSize: "1024MB" } })
  app.post("/admin/api/upload", upload.any(), async (req, res) => {
    const {
      files,
      body: { name },
    } = req
    let url = []
    console.log(req.body)
    files.forEach(async (file) => {
      let dest
      fileName = name + file.detectedFileExtension
      if (file.detectedFileExtension === ".webp") {
        //单张头像
        file.url = `http://localhost:3000/upload/temp/${fileName}`
        dest = `${__dirname}/../../upload/temp`
        res.send(file)
      } else {
        dest = `${__dirname}/../../upload`
        url.push(`http://localhost:3000/upload/${fileName}`)
      }
      // 写入文件流
      await pipeline(file.stream, fs.createWriteStream(`${dest}/${fileName}`))
    })
    url.length ? res.send(url) : console.log(url)
  })
}
